<template>
	<view>
		<view class="top">
      <view class="search-bg flex-center">
        <input type="text" class="w-100p" placeholder="请输入搜索内容" v-model="keyword">
        <view class="iconfont search-btn" @click="searchClick">&#xe661;</view>
      </view>
    </view>
		<view class="locate flex-center-between">
			<view>
				<view class="font15">精品咖啡沙龙</view>
				<view class="font12">
					<text>距离您</text>
					<text class="gray">7.9km</text>
				</view>
			</view>
			<view class="tabs-container">
				<view class="tabs">
					<view class="tab" :class="{ active: activeTab === 0 }" @click="setActiveTab(0)">自取</view>
					<view class="tab" :class="{ active: activeTab === 1 }" @click="setActiveTab(1)">快递</view>
				</view>
				<view class="indicator" :style="indicatorStyle"></view>
			</view>
		</view>
		<view class="base flex" :style="{height: containerHeight + 'px'}">
			<!-- 左侧分类列表 -->
			<scroll-view class="left" :scroll-y="true" :scroll-with-animation="true" :scroll-top="leftScrollTop">
				<view v-for="(cate, index) in cateList" :key="cate.categoryId"
					:class="['cate-item', { active: currentCateIndex === index }]" @click="handleCateClick(index)">
					{{ cate.categoryName }}
				</view>
			</scroll-view>
			<!-- 右侧商品列表 -->
			<scroll-view class="right" :scroll-y="true" :scroll-with-animation="true" :scroll-into-view="currentScrollId"
				@scroll="handleRightScroll">
				<view v-for="(cate, index) in cateList" :id="`cate-${index}`" :key="cate.categoryId" class="goods-group">
					<view class="group-title bolder">{{ cate.categoryName }}</view>
					<view v-for="item in cate.goods" :key="item.id" class="goods-cell mb20">
						<view class="flex-between">
							<view>
								<view>{{ item.name }}</view>
								<view class="font18 bolder">￥{{item.price}}</view>
							</view>
							<view>
                <image class="good-img mb10" mode="aspectFit"  :src="getImageUrl(item.mainImgs)"></image>
                <view class="flex-center-end action-btn">
                  <view class="iconfont minus gray" v-if="item.choseCount>0" @click="minusClick(item)">&#xe68b;</view>
                  <view class="result gray" v-if="item.choseCount>0">{{item.choseCount}}</view>
                  <view class="iconfont add gray" @click="addClick(item)">&#xe68a;</view>
                </view>
              </view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
    <cart-draft v-if="cartShowFlag" :page-show-flag="cartShowFlag" @showOrder="showOrder"></cart-draft>
    <cart-panel v-if="showOrderFlag" :page-show-flag="showOrderFlag" @reload="getCartData"></cart-panel>
	</view>
</template>

<script>
import CartDraft from "@/pages/cart/components/cartDraft.vue";
import {addDishToCart, getDishList,getCartList} from "@/api";
import {Validate} from "@/config/validate";
import {mapState} from 'vuex';
import {getStore} from "@/config/util";
import {mainData} from "@/pages/cart/components/mainData";
import CartPanel from "@/pages/cart/components/cartPanel.vue";
	export default {
		name: "index",
    components: {CartDraft,CartPanel},
		data() {
			return {
        userInfo:{},
        cartShowFlag:false,
				activeTab: 0, // 默认选中第一个选项卡
				leftItemHeights: [], // 存储左侧分类项高度
				leftItemPositions: [], // 存储左侧分类项累计高度
        keyword:'',
				indicatorStyle: {
					left: '0rpx', // 初始位置
					width: '100rpx' // 指示器的宽度
				},
				cateList: [], // 分类数据
				currentCateIndex: 0, // 当前选中分类索引
				currentScrollId: '', // 当前滚动目标ID
				leftScrollTop: 0, // 左侧滚动位置
				containerHeight: 0, // 容器高度
				catePositions: [], // 存储各分类的垂直位置信息
				scrollTimer: null,
        showOrderFlag:false,
			}
		},
		watch: {
			cateList() {
				this.initCatePositions()
			}
		},
    computed:{

    },
		mounted() {
			this.activeTab = mainData.cartData.takeType;
			this.calculateHeight()
			this.cacheLeftPositions() // 新增
      this.getList();
      this.userInfo = getStore('userInfo',1)||{};
      this.getCartData();
		},
		beforeDestroy() {
			this.observer && this.observer.disconnect()
		},
		methods: {
      getList(){
        getDishList().then(res=>{
          let cates = res.data;
          if (!Validate.isEmpty(cates)){
            let arr = [];
            cates.forEach(e=>{
              let dic = {...e};
              dic.goods = e.goods.map(v=>({...v,choseCount:0}));
              arr.push(dic);
            });
            this.cateList = arr;
          }
          this.initCatePositions();
        });
      },
      searchClick(){

      },
      addClick(row){
        this.cartShowFlag = true;
        row.choseCount ++;
        console.log(this.userInfo)
        let dic = {customerId:this.userInfo.id,goodsCart:[{goodsId:row.id,num:row.choseCount}]};
        addDishToCart(dic).then(res=>{
					this.getCartData();
        });
      },
      minusClick(row){
        row.choseCount --;
      },
			getCartData(){
				let dic =  {customerId:this.userInfo.id}
				getCartList(dic).then(res=>{
					mainData.cartData = res.data||{};
          if(!Validate.isEmpty(res.data.goods)){
            this.cartShowFlag = true;
          }
				});
			},
			// 在数据加载完成后调用
			initCatePositions() {
				this.$nextTick(() => {
          const query = uni.createSelectorQuery().in(this)
          this.cateList.forEach((_, index) => {
            query.select(`#cate-${index}`).boundingClientRect()
          })

          query.exec(res => {
            let accumHeight = 0
            this.catePositions = res.map(rect => {
              const position = {
                start: accumHeight,
                end: accumHeight + (rect?.height || 0)
              }
              accumHeight += rect?.height || 0
              return position
            })
          })
				})
			},
			calculateCurrentCate(scrollTop) {
				// 使用二分查找优化性能
				let low = 0
				let high = this.catePositions.length - 1

				while (low <= high) {
					const mid = Math.floor((low + high) / 2)
					const pos = this.catePositions[mid]

					if (scrollTop >= pos.start && scrollTop < pos.end) {
						if (this.currentCateIndex !== mid) {
							this.currentCateIndex = mid
							this.adjustLeftScroll(mid)
						}
						return
					} else if (scrollTop >= pos.end) {
						low = mid + 1
					} else {
						high = mid - 1
					}
				}
			},
			setActiveTab(index) {
				mainData.cartData.takeType = index;
				this.activeTab = index;
				this.updateIndicatorPosition(index);
			},
			updateIndicatorPosition(index) {
				const tabWidth = 200; // 每个选项卡的宽度 (rpx)
				const indicatorWidth = 100; // 黑色部分的宽度 (rpx)
				this.indicatorStyle = {
					left: `${tabWidth * index}rpx`, // 计算新的位置
					width: `${indicatorWidth}rpx` // 保持宽度不变
				};
			},
			// 初始化容器高度
			calculateHeight() {
				// 获取系统信息（同步方法）
				const systemInfo = uni.getSystemInfoSync()
				const query = uni.createSelectorQuery().in(this)
				// 查询关键节点
				query.select('.top').boundingClientRect()
				query.select('.locate').boundingClientRect()
				query.exec(res => {
					const topHeight = res[0].height
					const locateHeight = res[1].height
					// 核心计算公式
					this.containerHeight = systemInfo.windowHeight - topHeight - locateHeight
				})
			},
			// 点击左侧分类
			handleCateClick(index) {
				this.currentCateIndex = index
				this.currentScrollId = `cate-${index}`
				this.adjustLeftScroll(index)
			},

			// 调整左侧滚动位置
			adjustLeftScroll(index) {
			  if (!this.leftItemPositions.length) return
			  
			  // 获取容器尺寸
			  const query = uni.createSelectorQuery().in(this)
			  query.select('.left').boundingClientRect()
			  query.exec(res => {
			    const container = res[0]
			    if (!container) return
			    
			    // 目标项位置信息
			    const itemTop = this.leftItemPositions[index]
			    const itemHeight = this.leftItemPositions[index + 1] ? 
			      this.leftItemPositions[index + 1] - itemTop : 
			      this.leftItemPositions[index] - (this.leftItemPositions[index - 1] || 0)
			    
			    // 计算理想滚动位置（垂直居中）
			    const targetScroll = itemTop - (container.height / 2) + (itemHeight / 2)
			    
			    // 边界控制
			    const maxScroll = this.leftItemPositions[this.leftItemPositions.length - 1] - container.height
			    const finalScroll = Math.max(0, Math.min(targetScroll, maxScroll))
			    
			    // 平滑滚动
			    this.leftScrollTop = finalScroll
			    this.$nextTick(() => {
			      this.leftScrollTop = finalScroll + 0.01 // 确保触发滚动
			    })
			  })
			},

			// 监听右侧滚动  优化后的滚动处理
			handleRightScroll(e) {
			  if (this.scrollTimer) clearTimeout(this.scrollTimer)
			  this.scrollTimer = setTimeout(() => {
			    // 添加容错处理
			    const safeScrollTop = Math.max(0, e.detail.scrollTop)
			    this.calculateCurrentCate(safeScrollTop)
			  }, 80) // 调整为更合适的节流时间
			},
			// 新增缓存方法
			cacheLeftPositions() {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this)
					query.selectAll('.cate-item').boundingClientRect()
					query.exec(res => {
						let accum = 0
						this.leftItemPositions = res[0].map(item => {
							const position = accum
							accum += item.height
							return position
						})
					})
				})
			},
      showOrder(){
        this.showOrderFlag = true;
      }
		}
	}
</script>

<style lang="scss" scoped>
.w-100p{
  width: 100%;
}
	.top {
		background-color: #D2ABCC;
		width: 100%;
		height: 250rpx;
    padding-top: 160rpx;
    .search-bg{
      background-color: white;
      border-radius: 10rpx;
      height: 65rpx;
      width: 630rpx;
      margin-left: 60rpx;
      padding: 0 20rpx;
      .search-btn{
        width: 80rpx;
        text-align: center;
      }
    }
	}

	.locate {
		padding: 10rpx 20rpx;
	}

	.tabs-container {
		width: fit-content;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		background-color: #DCDCDC;
		border-radius: 28rpx;

		.tabs {
			display: flex;
			position: relative;
		}

		.tab {
			padding: 6rpx 20rpx;
			text-align: center;
			font-size: 32rpx;
			color: #333;
			cursor: pointer;
			border-radius: 28rpx;
		}

		.tab.active {
			color: #fff;
			background-color: #000;
		}

		.indicator {
			position: absolute;
			bottom: 0;
			height: 4rpx;
			background-color: #000;
			transition: left 0.3s ease;
			/* 动画效果 */
		}
	}

	.base {
		overflow: hidden;

		.left,
		.right {
			height: 100%; // 关键：继承父容器高度
			box-sizing: border-box; // 防止padding影响计算
		}

		.left {
			height: 100%;
			width: 190rpx;
			background: #fff;
      border-top-right-radius: 20rpx;
      overflow: hidden;
			.cate-item {
				padding: 40rpx 20rpx 40rpx 20rpx;
        border-bottom: 1rpx solid var(--bg);
				&.active {
					background: #fff;
					color: #ff5000;
					font-weight: bold;
				}
			}
		}

		.right {
			flex: 1;
			height: 100%;
			padding-left: 20rpx;
			padding-right: 20rpx;

			.goods-group {
				margin-bottom: 30rpx;

				.group-title {
					font-size: 32rpx;
					padding: 20rpx 0;
					border-bottom: 1px solid #eee;
				}

				.goods-cell {
					background-color: white;
					border-radius: 20rpx;
					padding: 20rpx;

					.good-img {
						width: 230rpx;
						height: 230rpx;
						border-radius: 15rpx;
						flex-shrink: 0;
					}
          .action-btn{
            .minus ,.add{
              font-size: 50rpx !important;
            }
            .result{
              min-width: 80rpx;
              text-align: center;
            }
          }
				}
			}
		}
	}
</style>